﻿using System.Diagnostics;
using System.Text;

namespace LuckyFish.GitNet.ConsoleServes;

public static class TerminalServer
{
    // public string FolderPath { get; private set; }
    // public TerminalServer(string path)
    // {
    //     FolderPath = path;
    // }

    public static string InputOrder(string order)
    {
        Process a = new Process();
        a.StartInfo.FileName = TerminalPath;
        a.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
        a.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
        a.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
        a.StartInfo.RedirectStandardError = true; //重定向标准错误输出
        a.Start();
        a.StandardInput.WriteLine(order); //指令
        a.StandardInput.Close();
        a.StandardOutput.ReadLine();
        a.StandardOutput.ReadLine();
        a.StandardOutput.ReadLine();
        a.StandardOutput.ReadLine();
        return a.StandardOutput.ReadToEnd();
    }

    public static string TerminalPath => OperatingSystem.IsWindows() ? "cmd.exe" : "/bin/bash";
}


public class CommandRunner
{
    public StringBuilder RecordBuilder { get; set; }
    private string ExecutablePath { get; }
    private string? WorkingDirectory { get; }

    public CommandRunner(string? executablePath, string? workingDirectory = null)
    {
        RecordBuilder = new StringBuilder();
        ExecutablePath = executablePath ?? throw new ArgumentNullException(nameof(executablePath));
        WorkingDirectory = workingDirectory ?? Path.GetDirectoryName(executablePath);
    }

    public string Run(string arguments)
    {
        var info = new ProcessStartInfo(ExecutablePath, arguments)
        {
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            UseShellExecute = false,
            WorkingDirectory = WorkingDirectory,
        };
        var process = new Process
        {
            StartInfo = info,
        };
        process.Start();
        RecordBuilder.Append($"{arguments}\n");
        return process.StandardOutput.ReadToEnd();
    }
}